package com.example.backend.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.common.api.R;
import com.example.backend.entity.User;
import com.example.backend.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.example.backend.common.annotation.OperationLog;
import com.example.backend.dto.UserDTO;
import org.springframework.validation.annotation.Validated;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/admin/user")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:user:list')")
    public R<Page<User>> list(@RequestParam(defaultValue = "1") Integer current,
                             @RequestParam(defaultValue = "10") Integer size,
                             String keyword) {
        Page<User> page = userService.page(new Page<>(current, size),
                new LambdaQueryWrapper<User>()
                        .like(keyword != null, User::getUsername, keyword)
                        .or()
                        .like(keyword != null, User::getNickname, keyword)
                        .orderByDesc(User::getCreateTime));
        return R.ok(page);
    }
    
    @OperationLog(module = "用户管理", type = "新增", description = "新增用户")
    @PostMapping
    @PreAuthorize("hasAuthority('system:user:add')")
    public R<Void> createUser(@Validated(UserDTO.Create.class) @RequestBody UserDTO userDTO) {
        userService.createUser(userDTO);
        return R.ok();
    }
    
    @OperationLog(module = "用户管理", type = "修改", description = "修改用户")
    @PutMapping
    @PreAuthorize("hasAuthority('system:user:edit')")
    public R<Void> updateUser(@Validated(UserDTO.Update.class) @RequestBody UserDTO userDTO) {
        userService.updateUser(userDTO);
        return R.ok();
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public R<Void> delete(@PathVariable Long id) {
        return userService.deleteUser(id) ? R.ok() : R.fail("删除失败");
    }
    
    /**
     * 重置密码
     */
    @PutMapping("/{id}/password")
    @PreAuthorize("hasAuthority('system:user:reset')")
    public R<Void> resetPassword(@PathVariable Long id, @RequestParam String newPassword) {
        return userService.resetPassword(id, newPassword) ? R.ok() : R.fail("重置失败");
    }
} 